package com.zyx.concurrentdemo.mytest.c08;

import com.zyx.concurrentdemo.c02basic.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Yaxi.Zhang
 * @since 2021/10/21 09:47
 * desc: CountDownLatch案例
 */
@SuppressWarnings({"AlibabaAvoidManuallyCreateThread", "AlibabaThreadPoolCreation"})
@Slf4j(topic = "c.CountDownLatchDemo")
public class CountDownLatchDemo {

    public static void main(String[] args) {
        test2();
    }

    public static void test2() {
        log.debug("waiting...");
        AtomicInteger ai = new AtomicInteger(0);
        int loop = 10;
        CountDownLatch latch = new CountDownLatch(loop);
        ExecutorService pool = Executors.newFixedThreadPool(loop, (r) -> new Thread(r, "t" + ai.incrementAndGet()));
        String[] progressBars = new String[loop];
        Random random = new Random();
        for (int i = 0; i < loop; i++) {
            int x = i;
            pool.submit(() -> {
                for (int j = 0; j < 100; j++) {
                    Sleeper.sleep(random.nextInt(100) / 1000.0);
                    progressBars[x] = Thread.currentThread().getName() + "(" + (j + 1) + "%)";
                    System.out.print("\r" + Arrays.toString(progressBars));
                }
                latch.countDown();
            });
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("\ngame starts...");
    }

    public static void test1() {
        CountDownLatch latch = new CountDownLatch(3);
        Thread t1 = new Thread(() -> {
            log.debug("begin...");
            Sleeper.sleep(1);
            latch.countDown();
            log.debug("end, remaining {}", latch.getCount());
        }, "t1");

        Thread t2 = new Thread(() -> {
            log.debug("begin...");
            Sleeper.sleep(1.5);
            latch.countDown();
            log.debug("end, remaining {}", latch.getCount());
        }, "t2");

        Thread t3 = new Thread(() -> {
            log.debug("begin...");
            Sleeper.sleep(2);
            latch.countDown();
            log.debug("end, remaining {}", latch.getCount());

        }, "t3");

        t1.start();
        t2.start();
        t3.start();


        log.debug("main wait...");
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.debug("main start...");
    }

}
